package org.fall.mvc.handler;

import crowd.entity.Menu;
import org.fall.service.api.MenuService;
import org.fall.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author XZ
 * @create 2021-12-14 09:35
 */
@Controller
public class MenuHandle {
    @Autowired
    private MenuService menuService;

    @ResponseBody
    @RequestMapping("/menu/do/get.json")
    public ResultEntity<Menu> getWholeTreeNew() {
        // 通过service层方法得到全部Menu对象的List
        List<Menu> menuList = menuService.getAll();

        // 声明一个Menu对象root，用来存放找到的根节点
        Menu root = null;

        // 使用map表示每一个菜单与id的对应关系
        Map<Integer, Menu> menuMap = new HashMap<>();

        // 将菜单id与菜单对象以K-V对模式存入map
        for (Menu menu : menuList) {
            menuMap.put(menu.getId(), menu);
        }

        for (Menu menu : menuList) {
            Integer pid = menu.getPid();
            if (pid == null) {
                root = menu;
                continue;
            }
            Menu father = menuMap.get(pid);
            father.getChildren().add(menu);
        }
        // 将根节点作为data返回（返回根节点也就返回了整棵树）
        return ResultEntity.successWithData(root);
    }

    @ResponseBody
    @RequestMapping("/menu/save.json")
    public ResultEntity<String> saveMenu(Menu menu){

        menuService.saveMenu(menu);

        return ResultEntity.successWithoutData();
    }

    @ResponseBody
    @RequestMapping("/menu/edit.json")
    public ResultEntity<String> editMenu(Menu menu){
        menuService.editMenu(menu);
        return ResultEntity.successWithoutData();
    }

    @ResponseBody
    @RequestMapping("/menu/remove.json")
    public ResultEntity<String> removeMenu(Integer id){
        menuService.removeMenuById(id);
        return ResultEntity.successWithoutData();
    }
}